# -*- coding: utf-8 -*-

import os
import pymysql

ScriptType_None         = 0
ScriptType_AIGraphml    = 1
ScriptType_CharSpawn    = 2
ScriptType_CharDead     = 3
ScriptType_CharPlay     = 4
ScriptType_SObjSpawn    = 11
ScriptType_SObjPlay     = 12
ScriptType_QuestReq     = 21
ScriptType_QuestInit    = 22
ScriptType_QuestReward  = 23
ScriptType_QuestEvent   = 24
ScriptType_CanCastSpell = 31
ScriptType_UseItem      = 41

def sync2db(conn, tgtfile, type):
    cursor = conn.cursor()
    tgtfile = tgtfile.replace('\\', '/')
    cursor.execute('SELECT COUNT(*) FROM `scriptable` WHERE '+
        '`scriptType`=%s AND `scriptFile`=%s', (type, tgtfile))
    if cursor.fetchone()[0] == 0:
        cursor.execute('INSERT INTO `scriptable` VALUES(NULL,%s,%s)',
            (type, tgtfile))
    cursor.close()

def importgraphml2db(conn, indir, tgtdir, type):
    if tgtdir is None:
        tgtdir = indir

    def importreference2db(name):
        infile = os.path.abspath(os.path.join(indir, name))
        with open(infile, 'r') as fp:
            lines = [line.strip() for line in fp.readlines()]
        for name in lines[1:]:
            if not name: continue
            tgtfile = os.path.join(tgtdir,
                os.path.splitext(os.path.basename(name))[0] + ".graphml.lua")
            sync2db(conn, tgtfile, type)

    for name in os.listdir(indir):
        if os.path.isdir(os.path.join(indir, name)):
            importgraphml2db(conn,
                os.path.join(indir, name), os.path.join(tgtdir, name), type)
        elif os.path.isfile(os.path.join(indir, name)):
            if name.endswith('.graphml'):
                sync2db(conn, os.path.join(tgtdir, name)+'.lua', type)
            elif name.endswith('.reference'):
                importreference2db(name)

def importfile2db(conn, indir, tgtdir, type):
    if tgtdir is None:
        tgtdir = indir
    for name in os.listdir(indir):
        if os.path.isdir(os.path.join(indir, name)):
            importfile2db(conn,
                os.path.join(indir, name), os.path.join(tgtdir, name), type)
        elif os.path.isfile(os.path.join(indir, name)):
            sync2db(conn, os.path.join(tgtdir, name), type)

if __name__ == '__main__':
    conn = pymysql.connect(host='127.0.0.1', user='app', password='123456',
        database='mmorpg_world', port=3306, charset='utf8mb4')
    try:
        importgraphml2db(conn, 'graphml', None, ScriptType_AIGraphml)
        importfile2db(conn, 'scripts/SObj/Play', None, ScriptType_SObjPlay)
        conn.commit()
    finally:
        conn.close()
